﻿using AutoMapper;
using B.S.BasicData.Api.Write.Application.Command.Approval;
using B.S.BasicData.Domain;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MediatR;

namespace B.S.BasicData.Api.Write.Application.Handler.Approval
{
    public class UpdateApprovalStateHandler : IRequestHandler<UpdateApprovalStateCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<ApprovalModel> approvalRepo;

        public UpdateApprovalStateHandler(IBaseRepository<ApprovalModel> approvalRepo)
        {
            this.approvalRepo = approvalRepo;
        }
        public Task<ApiResult<int>> Handle(UpdateApprovalStateCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();
            var approval = approvalRepo.GetAll().Where(x => x.Id == request.Id && !x.IsDelete).FirstOrDefault();
            if (approval==null)
            {
                res.Msg = "没有找到对应的记录";
                res.Code = ApiEnum.Error;
                return Task.FromResult(res);
            }
            if (request.ApprovalState==true)
            {
                approval.ApprovalState = true;
                approval.ApprocalYuan = null;
            }
            else if (request.ApprovalState==false)
            {
                if (string.IsNullOrEmpty(request.ApprocalYuan))
                {
                    res.Code = ApiEnum.Error;
                    res.Msg = "请填写原因";
                }
                approval.ApprovalState=true;
                approval.ApprocalYuan = request.ApprocalYuan;
                
            }
            approvalRepo.Update(approval);
            res.Msg = "审批成功";
            res.Code = ApiEnum.Success;
            return Task.FromResult(res);
        }
    }
}
